package com.vernon.demo.controller;

import com.google.common.collect.Lists;
import com.vernon.demo.utils.PmUtil;
import com.vernon.demo.utils.UuidGenerator;
import com.vernon.demo.model.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.function.Supplier;

@RestController
public class HelloController {

    static public List<Long> cache = Lists.newArrayList();
    static UuidGenerator generator = null;

    static public List<String> bizCache = Lists.newArrayList();
    static public List<String> pressureCache = Lists.newArrayList();

    static {
        generator = new UuidGenerator(1, 1, 1);
        onDestroy();
    }

    /**
     * 过滤掉压测流量写入本地缓存
     *
     * @return
     */
    @GetMapping("/hello")
    public Result<String> hello() {
        return supplier(() -> {
            if (PmUtil.isPressureMeasurement()) {
                return Result.success("filter to put pressure flow into local cache.");
            }
            long nextId = generator.nextId();
            cache.add(nextId);
            return Result.success("biz flow put next id into local cache success , next id is " + nextId);
        });
    }

    public <T> T supplier(Supplier<T> supplier) {
        return supplier.get();
    }

    static void onDestroy() {
    }

    @GetMapping("filterMap")
    public Result<String> filterMap() {
        return supplier(() -> {
            if (PmUtil.isPressureMeasurement()) {
                bizCache.add(generator.generate());
                return Result.success("filter to put pressure flow into local cache.");
            }
            String nextId = generator.generate();
            pressureCache.add(generator.generate());
            return Result.success("biz flow put next id into local cache success , next id is " + nextId);
        });

    }

}
